// src/utils/alipayOrderUtils.ts
export const btoaReactNative = (str: string): string => {
    const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    let result = '';
    let i = 0;
    let charCode: number;
    let bytes: number[] = [];

    // 1. 字符串转UTF-8字节数组
    for (let j = 0; j < str.length; j++) {
        charCode = str.charCodeAt(j);
        if (charCode < 0x80) {
            bytes.push(charCode);
        } else if (charCode < 0x800) {
            bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
        } else if (charCode < 0xd800 || charCode >= 0xe000) {
            bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
        } else {
            j++;
            charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(j) & 0x3ff));
            bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
        }
    }

    // 2. 字节数组转Base64
    let chunk: number;
    for (i = 0; i < bytes.length; i += 3) {
        chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
        result += base64Chars[(chunk >> 18) & 0x3f];
        result += base64Chars[(chunk >> 12) & 0x3f];
        result += base64Chars[(chunk >> 6) & 0x3f];
        result += base64Chars[chunk & 0x3f];
    }

    // 3. 处理填充字符
    const padding = bytes.length % 3;
    if (padding === 1) result = result.slice(0, -2) + '==';
    else if (padding === 2) result = result.slice(0, -1) + '=';

    return result;
};

export const generateOrderNo = (): string => {
    const timestamp = Date.now().toString().slice(-10);
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); 
    return `DEMO${timestamp}${random}`;
};

/**
 * 构建支付宝订单信息（模拟参数排序和签名）
 */
export const buildAlipayOrderInfo = (): string => {
    const params = {
        app_id: "2021000000000000", 
        biz_content: JSON.stringify({
            out_trade_no: generateOrderNo(), // 订单号
            total_amount: "0.01", // 订单金额
            subject: "测试商品", // 商品描述
            product_code: "QUICK_MSECURITY_PAY" // 固定值（APP支付）
        }),
        charset: "UTF-8",
        format: "json",
        method: "alipay.trade.app.pay",
        sign_type: "RSA2",
        timestamp: new Date().toISOString().replace(/T/, ' ').split('.')[0],
        version: "1.0"
    };

    // 参数按字母排序并拼接
    const sortedKeys = Object.keys(params).sort();
    const signContent = sortedKeys.map(key => `${key}=${params[key as keyof typeof params]}`).join('&');
    
    // 模拟RSA2签名
    const encodedStr = unescape(encodeURIComponent(signContent));
    const mockSign = btoaReactNative(encodedStr).slice(0, 64);
    
    return `${signContent}&sign=${mockSign}`;
};